// pages/order/order.js
var app = getApp();
import { orderMy, weChatPay, delOrder, gettedOrder } from '../../config/https';
import Dialog from '../../vant/dialog/dialog';
import Notify from '../../vant/notify/notify';
import Toast from '../../vant/toast/toast';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    navActive: 0, //	当前激活标签的索引
    swipeable: true, //开启手势滑动切换
    refresh: true
  },

  initData() {
    this.setData({
      loading: false, //页面是否加载完成
      loadMore: false, //加载中提示
      finished: false, //是否已经请求完全部数据
      page: 0, //页码
      pagesize: 10, //分类数量
      totalPage: null, //总页数
      listData: [], //列表数据
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if (this.data.refresh){
      const navActive = this.options.type
      this.setData({ navActive })
      this.initData()
      this.init()
    }
  },

  init(page) {
    this.setData({
      loadMore: true
    })
    orderMy[this.data.navActive]({
      page: ++this.data.page,
      pagesize: this.data.pagesize,
      user_id: app.globalData.user_id
    }).then(res => {
      const listData = [...this.data.listData, ...res.result];
      this.setData({
        loading: true,
        totalPage: res.totalPage || 0,
        loadMore: false,
        finished: this.data.page < res.totalPage ? false : true,
        listData
      })
      // 停止下拉刷新
      wx.stopPullDownRefresh();
    })
  },

  //订单状态切换
  orderTypeTap(e){
    const navActive = e.detail.index
    this.setData({ navActive })
    this.initData()
    this.init()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  // 取消订单
  cancelTap(e){
    const index = e.currentTarget.dataset.index
    const item = this.data.listData[index]
    Dialog.confirm({
      message: '确定取消此订单吗？'
    }).then(() => {
      delOrder({
        user_id: app.globalData.user_id,
        order_id: item.id,
        status: item.status,
        type: 1,
      }).then(res => {
        this.succNot("取消订单成功")
        this.initData()
        this.init()
      }).catch(err => {
        this.failNot(err.msg || "取消订单失败")
      })
    }).catch(() => {
      // on cancel
    });
  },

  // 立即支付
  toPay(e) {
    Toast.loading({
      mask: true,
      duration: 0,
      message: '请稍后...'
    });
    const index = e.currentTarget.dataset.index
    const item = this.data.listData[index]
    const that = this
    weChatPay({
      user_id: app.globalData.user_id,
      order_number: item.order_number,
      total_price: item.realprices
    }).then(res => {
      Toast.clear()
      wx.requestPayment({
        'timeStamp': res.timeStamp,
        'nonceStr': res.nonceStr,
        'package': res.package, //
        'signType': 'MD5',
        'paySign': res.paySign,
        'success': res => {
          Toast.success('支付成功');
          setTimeout(() => {
            that.initData()
            that.init()
          }, 1000)
        },
        'fail': err => {
          that.failNot("支付失败,请重新支付")
        }
      })
    })
    // wx.navigateTo({
    //   url: `../payment/payment?data=${JSON.stringify(data)}`
    // })
  },

  // 确认收货
  delivery(e) {
    const index = e.currentTarget.dataset.index
    const item = this.data.listData[index]
    Dialog.confirm({
      message: '是否确认收货？'
    }).then(() => {
      gettedOrder({
        user_id: app.globalData.user_id,
        order_id: item.id
      }).then(res => {
        this.succNot("确认收货成功")
        this.initData()
        this.init()
      }).catch(err => {
        this.failNot(err.msg || "确认收货失败")
      })
    }).catch(() => {
      // on cancel
    });
  },

  // 立即评价
  estimate() {
    wx.navigateTo({
      url: '../evaluate/evaluate',
    })
  },

  // 删除订单
  deleteTap(e) {
    const index = e.currentTarget.dataset.index
    const item = this.data.listData[index]
    Dialog.confirm({
      zIndex: 110,
      message: '是否要删除订单？'
    }).then(() => {
      delOrder({
        user_id: app.globalData.user_id,
        order_id: item.id,
        status: item.status,
        type: 2,
      }).then(res => {
        this.succNot("删除订单成功")
        this.initData()
        this.init()
      }).catch(err => {
        this.failNot(err.msg || "删除订单失败")
      })
    }).catch(() => {
      // on cancel
    });
  },

  // 跳转详情
  toInfo(e){
    const id = e.currentTarget.dataset.id
    this.data.refresh = false  //从订单详情返回不会刷新页面
    wx.navigateTo({
      url: `../orderInfo/orderInfo?order_id=${id}`
    })
  },

  succNot(msg) {
    Notify({
      text: msg,
      backgroundColor: '#1989fa'
    });
  },

  failNot(msg) {
    Notify({
      text: msg,
      backgroundColor: '#f44'
    });
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.initData()
    this.init()
    wx.vibrateShort();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    if (!this.data.finished && !this.data.loadMore) {
      this.init()
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})